
package com.gitee.jmash.rbac.dao;

import com.crenjoy.proto.utils.TypeUtil;
import com.gitee.jmash.core.orm.jpa.SqlBuilder;
import com.gitee.jmash.core.orm.jpa.TenantEntityManager;
import com.gitee.jmash.core.orm.jpa.TreeBaseDao;
import com.gitee.jmash.rbac.entity.RoleEntity;
import com.gitee.jmash.rbac.model.TreeResult;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import jmash.rbac.protobuf.DutyType;
import jmash.rbac.protobuf.RoleReq;
import org.apache.commons.lang3.StringUtils;

/**
 * Role实体的Dao层（使用JPA实现）.
 *
 * @author <a href="mailto:service@crenjoy.com">crenjoy</a>
 */
public class RoleDao extends TreeBaseDao<RoleEntity, UUID> {

  public RoleDao() {
    super();
  }

  public RoleDao(TenantEntityManager tem) {
    super(tem);
  }

  /** 通过角色编码查询角色实体. */
  public RoleEntity findByCode(String roleCode) {
    return this.findSingle("select s from RoleEntity s where s.roleCode = ?1 ", roleCode);
  }

  /** 检查是否系统角色登录(无需验证码). */
  public boolean checkSystemRole(String directoryId, String userName) {
    String sql = " select s from RoleEntity s,UsersRolesEntity ur, UserEntity u "
        + " where s.roleId=ur.roleId and ur.userId= u.userId and "
        + " s.roleCode = ?1  and u.directoryId=?2 and u.loginName=?3 ";
    RoleEntity entity = this.findSingle(sql, RoleEntity.SYSTEM, directoryId, userName);
    return entity != null;
  }

  /**
   * 综合查询.
   */
  public List<RoleEntity> findListByReq(RoleReq req) {
    SqlBuilder sqlBuilder = createSql(req);
    String query = sqlBuilder.getQuerySql("select s ");
    return this.findListByParams(query, sqlBuilder.getParams());
  }



  /** 获取TreeResult. */
  public List<TreeResult> findTreeResultByReq(RoleReq req) {
    SqlBuilder sqlBuilder = createSql(req);
    String query = sqlBuilder
        .getQuerySql("select s.roleId as value,s.roleName as label,s.parentId as parentId ");
    return this.findDtoListByParams(query, TreeResult.class, sqlBuilder.getParams());
  }

  /** Create SQL By Req . */
  public SqlBuilder createSql(RoleReq req) {
    StringBuilder sql = new StringBuilder(" from RoleEntity s where 1=1  ");
    Map<String, Object> params = new HashMap<String, Object>();

    if (req.getHasRoleType()) {
      sql.append(" and s.roleType = :roleType ");
      params.put("roleType", req.getRoleType());
    }

    if (!TypeUtil.isEmpty(req.getCreateBy())) {
      sql.append(" and s.createBy = :createBy ");
      params.put("createBy", req.getCreateBy());
    }
    if (StringUtils.isNotBlank(req.getLikeRoleName())) {
      sql.append(" and s.roleName like :roleName ");
      params.put("roleName", "%" + req.getLikeRoleName() + "%");
    }
    if (StringUtils.isNotBlank(req.getRoleCode())) {
      sql.append(" and s.roleCode = :roleCode ");
      params.put("roleCode", req.getRoleCode());
    }

    String orderSql = " order by s.depth,s.orderBy  ";
    return SqlBuilder.build().setSql(sql).setParams(params).setOrderSql(orderSql);
  }

  /** 获取动态角色列表. */
  public List<RoleEntity> getDsdRoleList() {
    String sql = "select distinct s from RoleEntity s where  s.roleType = 'role' and exists "
        + "(select a.srcRoleId from RolesDutyEntity a where a.dutyType = :dutyType and (a.srcRoleId = s.roleId or  a.descRoleId = s.roleId ) )  order by s.depth,s.orderBy  ";
    return getEntityManager().createQuery(sql, RoleEntity.class)
        .setParameter("dutyType", DutyType.DSD).getResultList();
  }

  /** 根据角色编码查询角色. */
  public List<RoleEntity> roleListByCode(String roleCode) {
    String sql = "select s from RoleEntity s where s.roleCode = :roleCode";
    Map<String, Object> params = new HashMap<>();
    params.put("roleCode", roleCode);
    return this.findListByParams(sql, params);
  }

}
